<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="formData.customerName"
              placeholder="请输入客户名称"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户编号" prop="customerNo">
            <el-input
              v-model="formData.customerNo"
              placeholder="请输入客户编号"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目" prop="projectId">
            <el-select
              v-model="formData.version.projectId"
              placeholder="请选择项目"
              @change="onProjectChange"
              :disabled="formType == 'update'"
            >
              <el-option
                v-for="dict in projectList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本" prop="versionId">
            <el-select v-model="formData.versionId" placeholder="请输入版本">
              <el-option
                v-for="dict in projectVersionList"
                :key="dict.id"
                :label="dict.version"
                :value="dict.id"
                :disabled="formType == 'update'"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务器IP" prop="serverId">
            <el-select v-model="formData.serverId" placeholder="请输入服务器IP">
              <el-option
                v-for="dict in serverList"
                :key="dict.id"
                :label="dict.ip"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据库名称" prop="databaseName">
            <el-input
              v-model="formData.databaseName"
              placeholder="请输入数据库名称"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="同时在线账号数" prop="onlineAccountCount">
            <InputNumber
              v-model="formData.onlineAccountCount"
              placeholder="请输入同时在线账号数"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到期时间" prop="expiresTime">
            <el-date-picker
              v-model="formData.expiresTime"
              placeholder="请输入到期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="本地化部署" prop="isLocal">
            <el-checkbox v-model="formData.isLocal" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="DevopsCustomerEdit" lang="ts">
import * as DevopsCustomerApi from '@/api/infra/devops/customer'
import * as DevopsServerApi from '@/api/infra/devops/server'
import * as DevopsProjectVersionApi from '@/api/infra/devops/projectVersion'
import * as DevopsProjectApi from '@/api/infra/devops/project'
import { InputNumber } from '@/components/InputNumber'
let formType = ''
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const projectList = ref()
const serverList = ref()
const projectVersionList = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  id: undefined,
  version: {
    projectId: undefined
  },
  customerName: undefined,
  customerNo: undefined,
  isLocal: false,
  versionId: undefined,
  serverId: undefined,
  databaseName: undefined,
  onlineAccountCount: 5,
  expiresTime: undefined
})
const formRules = reactive({
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  customerNo: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  versionId: [{ required: true, message: '版本不能为空', trigger: 'change' }],
  serverId: [{ required: true, message: '服务器IP不能为空', trigger: 'change' }],
  databaseName: [{ required: true, message: '数据库名称不能为空', trigger: 'blur' }]
})
/** 打开弹窗 */
const open = async (type, id) => {
  projectList.value = await DevopsProjectApi.listQuery()
  serverList.value = await DevopsServerApi.listQuery()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  resetForm()
  formType = type
  if (type == 'update') {
    formData.value = await DevopsCustomerApi.singleGet(id)
    projectVersionList.value = await DevopsProjectVersionApi.getByProject(
      formData.value.version.projectId
    )
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    version: {
      projectId: undefined
    },
    isLocal: false,
    customerName: undefined,
    customerNo: undefined,
    versionId: undefined,
    serverId: undefined,
    databaseName: undefined,
    onlineAccountCount: 5,
    expiresTime: undefined
  }
  formRef.value?.resetFields()
  projectVersionList.value = []
}

const onProjectChange = async (projectId) => {
  projectVersionList.value = await DevopsProjectVersionApi.getByProject(projectId)
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    if (formType === 'create') {
      await DevopsCustomerApi.create(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await DevopsCustomerApi.update(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
